<template>
    <a-spin :spinning="loading">
        <component :is="id ? 'section' : 'a-card'">
            <section v-if="!id" slot="title">
                车辆管理
            </section>
            <section>
                <a-row v-if="!id" :gutter="16">
                    <a-col class="flex items-center" :span="span">
                        <span class="label">车牌号：</span>
                        <a-input v-model="vehicleLicenceNum" @keyup.enter="search" :max-length="50" class="flex-1"
                                 placeholder="请输入车牌号"></a-input>
                    </a-col>
                    <a-col class="flex items-center" :span="span">
                        <span class="label">服务商：</span>
                        <a-input v-model="vendorName" @keyup.enter="search" :max-length="50" class="flex-1"
                                 placeholder="请输入服务商名称"></a-input>
                    </a-col>
                    <a-col class="flex items-center" :span="span">
                        <a-button type="primary" @click="search">查询</a-button>
                        <a-button class="mx-8" @click="reset">重置</a-button>
                        <a href="javascript:;" @click="isExpand = !isExpand">{{ isExpand ? '收起' : '展开' }}</a>
                    </a-col>
                </a-row>
                <a-row v-show="isExpand" :gutter="16">
                    <a-col v-if="id" class="flex items-center" :span="span">
                        <span class="label">车牌号：</span>
                        <a-input v-model="vehicleLicenceNum" @keyup.enter="search" :max-length="50" class="flex-1"
                                 placeholder="请输入车牌号"></a-input>
                    </a-col>
                    <a-col class="flex items-center" :span="span">
                        <span class="label">注册时间：</span>
                        <a-range-picker
                            v-model="registeredTimeArr"
                            @change="search"
                            class="flex-1"
                        >
                        </a-range-picker>
                    </a-col>
                    <a-col class="flex items-center" :span="span">
                        <span class="label">车辆状态：</span>
                        <a-select v-model="status" allow-clear @change="search" class="flex-1"
                                  placeholder="请选择车辆状态">
                            <a-select-option v-for="item in vehicleStatusEnums" :key="item.value" :value="item.value">
                                {{ item.name }}
                            </a-select-option>
                        </a-select>
                    </a-col>
                    <a-col class="flex items-center" :span="span">
                        <span class="label">车型选择：</span>
                        <SelectVehicleType
                            class="flex-1 overflow-hidden"
                            placeholder="请选择车型"
                            v-model="vehicleTypeId"
                            :options="{allowClear: true}"
                            @change="search"
                        />
                    </a-col>
                    <a-col class="flex items-center" :span="span">
                        <span class="label">年检到期时间：</span>
                        <a-date-picker
                            @change="search"
                            v-model="annualTimeEnd"
                            class="flex-1"
                        />
                    </a-col>
                    <a-col class="flex items-center" :span="span">
                        <span class="label">交强险到期时间：</span>
                        <a-date-picker
                            @change="search"
                            v-model="clivtaExpireDateTimeEnd"
                            class="flex-1"
                        />
                    </a-col>
                    <a-col class="flex items-center" :span="span">
                        <span class="label">商业险到期时间：</span>
                        <a-date-picker
                            @change="search"
                            v-model="insuranceExpireDateTimeEnd"
                            class="flex-1"
                        />
                    </a-col>
                    <a-col v-if="id" class="flex items-center" style="margin-top: 4px;" :span="span">
                        <a-button type="primary" @click="search">查询</a-button>
                        <a-button class="mx-8" @click="reset">重置</a-button>
                    </a-col>
                </a-row>
                <a-table
                    :columns="columns"
                    :data-source="data"
                    :pagination="pagination"
                >
                    <section class="text-left" slot="carInfo" slot-scope="val, record">
                        <section class="font-bold">
                            <a-tag color="#1890ff" class="text-18 py-4">{{ record.vehicleLicenceNum }}</a-tag>
                        </section>
                        <section class="font-bold text-16">{{ record | getVehicleTypeName }}</section>
                        <section class="text-14">车架号：{{ record.frameNum }}</section>
                        <section class="text-14">发动机号：{{ record.engineNum }}</section>
                    </section>
                    <section slot="storeInfo" slot-scope="val, record">
                        <section>{{ record.storeName }}</section>
                        <section class="text-12">{{ record.storeCityName }}</section>
                    </section>
                    <template #carImg="val, record">
                        <div class="flex justify-center">
                            <img @click="isPreviewVisible = true; previewImage = record.pcImgUrl" :src="record.pcImgUrl"
                                 alt=""
                                 class="w-80 h-80 br5 object-cover mx-5 ss-img cursor-pointer">
                            <img @click="isPreviewVisible = true; previewImage = record.mobileImgUrl"
                                 :src="record.mobileImgUrl"
                                 alt="" class="w-80 h-80 br5 object-cover mx-5 ss-img cursor-pointer"></div>
                    </template>
                    <template #drivingInfo="val, record">
                        <section>行驶里程：{{ record.currentMileage }}km</section>
                        <section>下次保养：{{ record.maintainMileage }}km</section>
                    </template>
                    <section slot="vendorInfo" slot-scope="val, record">
                        <section>{{ record.vendorName }}</section>
                        <section class="text-12">{{ record.storeName }}</section>
                    </section>
                    <template #status="status, record">
                        <section v-if="status === 1" class="success-color">营运中</section>
                        <section v-if="status === 2" class="grey">下架</section>
                        <section v-if="status === 3" class="warning-color">待审</section>
                        <a-tooltip v-if="status === 4" :title="`未通过理由：${record.auditRefusedReason}`">
                            <section class="error-color">审核拒绝</section>
                        </a-tooltip>
                        <section v-if="status === 5" class="warning-color">待提交</section>
                        <section v-if="status === 6" class="grey">强制下架</section>
                    </template>
                    <template #action="val, record, index">
                        <a v-if="record.status === 1 && $permissionJudge('StoreVehicleUpdate')"
                           href="javascript:void(0);" class="block" @click="updateShelf(record)">强制下架</a>
                        <a v-if="record.status === 6 && $permissionJudge('StoreVehicleUpdate')"
                           href="javascript:void(0);" class="block" @click="updateShelf(record)">恢复上架</a>
                        <a href="javascript:void(0);" class="block" @click="viewDetails(record)">车辆详情</a>
                        <a href="javascript:void(0);" class="block"
                           @click="currCarData = record; showHistoryModal = true">车辆历史</a>
                        <a href="javascript:void(0);" class="block" @click="showLog(record)">车辆日志</a>
                        <a href="javascript:void(0);" class="block" @click="editCarDetails(record)">车辆修改</a>

                    </template>
                </a-table>
            </section>
            <a-modal
                width="1060px"
                :dialog-style="{top: '30px'}"
                :body-style="{padding: '12px 24px'}"
                v-model="showCarInfoModal"
            >
                <section class="title" slot="title">
                    <span>车辆详情</span>
                    <section class="dot"/>
                    <span>{{ currCarData.vehicleLicenceNum }}</span>
                    <section class="dot"/>
                    <section class="flex items-center">
                        <a-tag v-if="currCarData.isInLease" class="tag primary-bg">租赁中</a-tag>
                        <a-tag v-if="currCarData.needMaintainStatus === 0 &&
                           currCarData.needInsuranceStatus === 0 &&
                           currCarData.needAnnuallyStatus === 0"
                               class="tag success-bg">
                            正常维保
                        </a-tag>
                        <!--保养状态-->
                        <a-tag
                            v-if="currCarData.needMaintainStatus !== 0"
                            class="tag primary-bg"
                            :class="{'warning-bg': currCarData.needMaintainStatus === 1,
                                'grey-bg': currCarData.needMaintainStatus === 4,}"
                        >{{ $utils.getEnumName(vehicleMaintainStatusEnums, currCarData.needMaintainStatus) }}
                        </a-tag>
                        <!--年检状态-->
                        <a-tag
                            v-if="currCarData.needAnnuallyStatus !== 0"
                            class="tag primary-bg"
                            :class="{'warning-bg': currCarData.needAnnuallyStatus === 2,
                                'grey-bg': currCarData.needAnnuallyStatus === 5,}"
                        > {{ $utils.getEnumName(vehicleMaintainStatusEnums, currCarData.needAnnuallyStatus) }}
                        </a-tag>
                        <!--续保状态-->
                        <a-tag
                            v-if="currCarData.needInsuranceStatus !== 0"
                            class="tag primary-bg"
                            :class="{
                'warning-bg': currCarData.needInsuranceStatus === 3,
              }"
                        >
                            {{ $utils.getEnumName(vehicleMaintainStatusEnums, currCarData.needInsuranceStatus) }}
                        </a-tag>
                        <!--						<a-tag class="tag warning-bg">待保养</a-tag>-->
                        <!--						<a-tag class="tag grey-bg">保养中</a-tag>-->
                        <!--						<a-tag class="tag warning-bg">待续保</a-tag>-->
                        <!--						<a-tag class="tag warning-bg">待年检</a-tag>-->
                        <!--						<a-tag class="tag grey-bg">年检中</a-tag>-->
                    </section>
                </section>
                <a-spin :spinning="detailsLoading">
                    <section style="padding-right: 8px; height: calc(100vh - 248px); overflow: auto;">
                        <CarInfo is-view :car-data="currCarData"/>
                    </section>
                </a-spin>
                <template #footer>
                    <a-button type="primary" @click="showCarInfoModal = false">好的</a-button>
                </template>
            </a-modal>
            <a-modal
                v-model="showHistoryModal"
                width="1200px"
                :dialog-style="{top: '30px'}"
                :body-style="{padding: '12px 24px'}"
            >
                <section slot="title" class="title">
                    <span>车辆历史</span>
                    <section class="dot"/>
                    <span>{{ currCarData.vehicleLicenceNum }}</span>
                </section>
                <HistoryList v-if="showHistoryModal" :vehicle-id="currCarData.id"/>
                <template #footer>
                    <a-button type="primary" @click="showHistoryModal = false">好的</a-button>
                </template>
            </a-modal>
            <a-modal v-model="isPreviewVisible" :footer="null">
                <div class="m-20">
                    <img class="mx-w-700 mx-h-700 w-full " :src="previewImage"/>
                </div>
            </a-modal>
            <a-modal
                v-model="showEditCarModal"
                width="1200px"
                @ok="submitEditCar"
                :dialog-style="{top: '30px'}"
                :body-style="{padding: '12px 24px'}"
            >
            <edit-travel-info v-if="showEditCarModal"
                              ref="editTravel"
                              :edit-color="true"
                              :isCarManage="true"
                              :base-car-data="currEditCarbaseData"
                              :car-data="currEditCarData"
                              @change="checkVehiceConfig"
                              @close="showEditCarModal = false"/>

            </a-modal>

        </component>
        <Log :type="2" ref="log">
            <section slot="title" class="title">
                <section>车辆日志</section>
                <section class="dot"/>
                <section>{{ currCarData.vehicleLicenceNum }}</section>
            </section>
        </Log>

    </a-spin>
</template>
<script>
  import {tableMixins} from '@/utils/mixins'
  import SelectVehicleType from '@/components/SelectVehicleType'
  import CarInfo from './CarInfo'
  import HistoryList from './HistoryList'
  import {
      getCarList,
      updateShelf,
      getCarDetails, getVehicleEdit
  } from '@/api/car-manage'
  import TravelInfo from "@/views/operationInfo/supplierManagement/store/store-info/TravelInfo.vue";
  import EditTravelInfo from "./TravelInfo.vue"
  // const  EditTravelInfo = () => import('./TravelInfo.vue')

  export default {
    name: 'CarManage',
    mixins: [tableMixins],
		props: {
    	id: {
    		type: [String, Number]
			}
		},
    components: {TravelInfo, SelectVehicleType, CarInfo, HistoryList, EditTravelInfo },
    data() {
      return {
	      span: 8,
        isExpand: false,
        isPreviewVisible: false,
        isEdit: false,
        showCarInfoModal: false,
        showHistoryModal: false,
        showEditCarModal: false,
        previewImage: '',
        loading: false,
        detailsLoading: false,
        vehicleLicenceNum: '',
        vehicleTypeId: undefined,
        vendorName: '',
        status: undefined,
        registeredTimeArr: [undefined, undefined],
        annualTimeEnd: undefined,
        clivtaExpireDateTimeEnd: undefined,
        insuranceExpireDateTimeEnd: undefined,
        currCarData: {},
        columns: [
          {title: '车辆信息', width: 300, dataIndex: 'carInfo', align: 'center', scopedSlots: {customRender: 'carInfo'}},
          {
            title: '门店信息',
            width: 160,
            dataIndex: 'storeInfo',
            align: 'center',
            scopedSlots: {customRender: 'storeInfo'}
          },
          {title: '车型图片', width: 260, dataIndex: 'carImg', align: 'center', scopedSlots: {customRender: 'carImg'}},
          {
            title: '行驶信息',
            width: 200,
            dataIndex: 'drivingInfo',
            align: 'center',
            scopedSlots: {customRender: 'drivingInfo'}
          },
          {
            title: '服务商',
            width: 160,
            dataIndex: 'vendorInfo',
            align: 'center',
            scopedSlots: {customRender: 'vendorInfo'}
          },
          {title: '车辆状态', width: 120, dataIndex: 'status', align: 'center', scopedSlots: {customRender: 'status'}},
          {
            title: '操作',
            width: 100,
            fixed: 'right',
            dataIndex: 'action',
            align: 'center',
            scopedSlots: {customRender: 'action'}
          }
        ],
        data: [],
        transmissionTypeEnums: [],
        vehicleMaintainStatusEnums: [],
        vehicleStatusEnums: [],
        currEditCarData: {},
        currEditCarbaseData: {},
      }
    },
    async created() {
      this.transmissionTypeEnums = await this.$utils.getDictList('TransmissionType')
      this.vehicleMaintainStatusEnums = await this.$utils.getDictList('VehicleMaintainStatus')
      this.vehicleStatusEnums = await this.$utils.getDictList('VehicleStatus')
      this.loading = true
			this.$watch('id', id => {
				if (id) {
					this.isExpand = true
					this.span = 12
					this.columns = this.columns.filter(e => e.dataIndex !== 'vendorInfo')
					this.columns.forEach(item => {
						if (item.width) item.width -= 20
					})
				}
			}, {immediate: true})
      this.getData()
    },
      methods: {
          search() {
              this.pageNum = 1
              this.getData()
          },
          reset() {
              this.vehicleLicenceNum = ''
              this.vehicleTypeId = undefined
              this.vendorName = ''
              this.status = undefined
              this.registeredTimeArr = [undefined, undefined]
              this.annualTimeEnd = undefined
              this.clivtaExpireDateTimeEnd = undefined
              this.insuranceExpireDateTimeEnd = undefined
              this.search()
          },
          showLog(data) {
              this.currCarData = data
              this.$refs.log.open(data.id)
          },
          getData() {
              this.loading = true
              getCarList({
                  pageNo: this.pageNum,
                  pageSize: this.rowsNum,
                  storeId: this.storeId,
                  vehicleLicenceNum: this.vehicleLicenceNum.trim(),
                  vehicleTypeId: this.vehicleTypeId,
                  vendorName: this.vendorName.trim(),
                  vendorId: this.id ? parseInt(this.id) : undefined,
                  status: this.status,
                  registeredTimeStart: this.$utils.getStartTime(this.registeredTimeArr[0]),
                  registeredTimeEnd: this.$utils.getEndTime(this.registeredTimeArr[1]),
                  annualTimeEnd: this.$utils.getEndTime(this.annualTimeEnd),
                  clivtaExpireDateTimeEnd: this.$utils.getEndTime(this.clivtaExpireDateTimeEnd),
                  insuranceExpireDateTimeEnd: this.$utils.getEndTime(this.insuranceExpireDateTimeEnd),
              }).then(data => {
                  this.data = data.items
                  this.total = data.rowCount
              }).finally(() => this.loading = false)
          },
          editCarDetails(data) {
              console.log(`editCarDetails data`, data)
              getCarDetails({id: data.id})
                  .then(res => {
                      console.log(`res`, res)
                      //排除内容为0和0001-01-01 00:00:00的数据
                      for (let key in res) {
                          if (res[key] === 0 || res[key] === '0001-01-01 00:00:00') {
                              res[key] = undefined
                          }
                      }
                      // res.vehicleConfigs = res.vehicleConfigs.split(',')
                      this.currEditCarData = res
                      this.currEditCarbaseData = data
                      this.showEditCarModal = true
                  })

          },
          async submitEditCar() {
              try {
                  const allData = await this.$refs.editTravel.GetFormAllValidate()
                  if (!allData) return;
                  this.loading = true;
                  const targetObj = {
                      vehicleId: this.currEditCarData.id,
                      // vehicleConfigs: this.currEditCarData.vehicleConfigs.join(','),
                      color: this.currEditCarData.color,
					  vehicleLicenceNum:allData[0].vehicleLicenceNum
                  }
                  console.log(`this.currEditCarData`,this.currEditCarData)
                  console.log(`targetObj`,targetObj)
                  const send = Object.assign({},allData[0],allData[1],allData[2],targetObj)
                  console.log(`send`, send)
				  // return
                  getVehicleEdit(send)
                      .then(res => {
                          this.$message.success('修改成功')
                          this.showEditCarModal = false
                          this.getData()
                      })
              } catch (e) {
                  console.log(`e`, e)

              } finally {
                  this.loading = false
              }
          },
          viewDetails(record) {
              this.showCarInfoModal = true
              this.detailsLoading = true
              getCarDetails({id: record.id}).then(data => {
                  this.currCarData = {
                      ...record,
                      ...data
                  }
              }).finally(() => this.detailsLoading = false)
          },
          updateShelf(data) {
              const isShelf = data.status !== 1
              if (!isShelf) {
                  this.$confirm({
                      title: '提示',
                      content: `请确认是否强制下架当前车辆？`,
                      okText: '确定',
                      okType: 'danger',
                      cancelText: '取消',
                      onOk: () => {
                          this.loading = true
                          updateShelf({id: data.id, isShelf}).then(() => {
                              this.loading = false
                              data.status = isShelf ? 1 : 6
                              this.$message.success('强制下架成功！')
                          }).finally(() => this.loading = false)
                      }
                  })
              } else {
                  this.loading = true
                  updateShelf({id: data.id, isShelf}).then(() => {
                      this.loading = false
                      data.status = isShelf ? 1 : 2
                      this.$message.success('恢复上架成功！')
                  }).finally(() => this.loading = false)
              }
          },
          deleteCar(data, index) {
              this.$confirm({
                  title: '提示',
                  content: '请确认是否删除当前车辆？',
                  okText: '确定',
                  okType: 'danger',
                  cancelText: '取消',
                  onOk: () => {
                      if (this.confirmLoading) return false
                      this.confirmLoading = true
                      deleteCar({id: data.id}).then(() => {
                          this.$message.success('删除成功！')
                          this.data.splice(index, 1)
                          if (this.data.length === 0 && this.pageNum > 1) this.pageNum--
                          this.getData()
                      }).finally(() => {
                          this.confirmLoading = false
                      })
                  }
              })
          },
          exportCarList() {
              exportCarList({
                  storeId: this.storeId,
                  vehicleLicenceNum: this.vehicleLicenceNum.trim(),
                  vehicleTypeId: this.vehicleTypeId,
                  vendorName: this.vendorName.trim(),
                  status: this.status
              }).then(data => {
                  console.log(data)
                  window.open(data.domain + data.filePath)
              })
          },
          selectCar(data) {
              this.carTypeData = data
              this.step = 1
          },
          submitSuccess() {
              this.showAddCarModal = false
              this.getData()
          },
          checkVehiceConfig(data) {
              // this.currEditCarData.vehicleConfigs = data
          },
      }
  }
</script>
<style lang="less" scoped>
  .label {
    width: 70px;
    text-align: right;
    margin-right: 4px;
  }

  .ss-img {
    border: 1px solid #d9d9d9
  }

  .title {
    display: flex;
    align-items: center;

    .dot {
      width: 4px;
      height: 4px;
      margin: 0 8px;
      border-radius: 50%;
      background: rgba(0, 0, 0, 0.65);
    }
  }

  .tag {
    display: block;
    width: 70px;
    padding: 4px 2px;
    text-align: center;
    color: #fff;
    margin: auto;
    margin-right: 8px;
    border: 0;
  }
	/deep/ .ant-col {
		margin-bottom: 16px;
	}
</style>
